package edu.lingnan.store.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.lingnan.store.common.ResultBean;
import edu.lingnan.store.entity.Goods;
import edu.lingnan.store.entity.Order;
import edu.lingnan.store.entity.OrderDetail;
import edu.lingnan.store.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * (Order)表控制层
 *
 * @author makejava
 * @since 2021-01-28 16:57:06
 */
@RestController
@RequestMapping("order")
public class OrderController {
    /**
     * 服务对象
     */
    @Resource
    private OrderService orderService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private ShopCartService shopCartService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private UserService userService;

    /**
     * 根据条件查询商品数据
     * @param page
     * @param limit
     * @param bean
     * @return
     */
    @GetMapping("list")
    public ResultBean getOrderData(Integer page, Integer limit, String bean){
        ResultBean resultBean = new ResultBean<>();
        Order order = JSONUtil.toBean(bean, Order.class);
        IPage<Order> iPage = orderService.queryAllByLimit(page,limit,order);
        Map<String, Object> map = new HashMap<>();
        map.put("total",iPage.getTotal());
        map.put("data",iPage.getRecords());
        resultBean.setData(map);
        return resultBean;
    }

    /**
     * 通过主键查询订单信息
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/info")
    public ResultBean getOrderInfo(@RequestParam("id") String id) {
        ResultBean resultBean = new ResultBean<>();
        if(id == null || id.equals("")){
            resultBean.setSuccess(false);
            return resultBean;
        }
        Order order = orderService.queryById(id);
        List<OrderDetail> details = orderDetailService.getDetailsByOrderId(id);
        Map<String, Object> map = new HashMap<>();
        map.put("order",order);
        map.put("details",details);
        resultBean.setData(map);
        return resultBean;
    }

    /**
     * 保存订单信息
     * @param orderJson
     * @return
     */
    @PostMapping("save")
    public ResultBean saveOrder(String orderJson, String detailsJson){
        Order order = JSONUtil.toBean(orderJson,Order.class);
        List<OrderDetail> orderDetails = JSONUtil.toList(detailsJson,OrderDetail.class);
        order.setCreateTime(new Date());
        //库存查询
        List<Goods> goods = this.goodsService.getStock(orderDetails);
        for(Goods good :goods){
            for(OrderDetail detail:orderDetails){
                //库存小于订单数量时
                if(good.getId().equals(detail.getGoodsId()) && good.getStock()<detail.getAmount()){
                    String msg = good.getName()+"库存不足！";
                    return new ResultBean(msg,false,null);
                }
            }
        }
        //创建订单
        String orderId = orderService.save(order,orderDetails);
        if(orderId==null){
            return new ResultBean("保存失败！",false,null);
        }
        //删除购物车
        for(OrderDetail detail:orderDetails){
            shopCartService.deleteCartByUserIdAndGoodsId(order.getUserId(),detail.getGoodsId());
        }
        return new ResultBean("保存成功！",true,orderId);
    }

    @GetMapping("/userOrders")
    public ResultBean getUserOrders(Integer userId,String status) {
        ResultBean resultBean = new ResultBean<>();
        List<Order> orders = orderService.queryOrderByUserIdAndStatus(userId, status);
        List<OrderDetail> details = orderDetailService.getDetailsByUserIdAndStatus(userId, status);
        Map<String, Object> map = new HashMap<>();
        map.put("orders",orders);
        map.put("orderDetails",details);
        resultBean.setData(map);
        return resultBean;
    }

    @GetMapping("/orderReminder")
    public ResultBean getOrdersByStatusAndPickupWay(String pickupWay,String status) {
        ResultBean resultBean = new ResultBean<>();
        List<Order> orders = orderService.getOrdersByStatusAndPickupWay(pickupWay, status);
        resultBean.setData(orders);
        return resultBean;
    }

    /**
     * 批量修改状态
     * @param map
     * @return
     */
    @PostMapping("updateStatus")
    public ResultBean updateStatus(@RequestBody HashMap<String, Object> map){
        ResultBean<Order> resultBean = new ResultBean<>();
        String status = (String) map.get("status");
        String[] ids = JSONUtil.toList(map.get("ids").toString(),String.class).toArray(new String[0]);
        if( ids == null || ids.length == 0){
            resultBean.setSuccess(false);
            resultBean.setMsg("请选择需要修改的数据！");
            return resultBean;
        }
        resultBean.setSuccess(orderService.changeOrderStatus(ids,status));
        if(!resultBean.isSuccess()){
            resultBean.setMsg("操作失败！");
            return resultBean;
        }
        resultBean.setMsg("操作成功！");
        return resultBean;
    }

    /**
     * 收货操作
     * @param idsJson
     * @return
     */
    @PostMapping("finishOrder")
    public ResultBean finishOrder(String idsJson){
        ResultBean<Order> resultBean = new ResultBean<>();
        String[] ids = JSONUtil.toList(idsJson,String.class).toArray(new String[0]);
        boolean flag = true;
        if( ids == null || ids.length == 0){
            resultBean.setSuccess(false);
            resultBean.setMsg("收货失败！");
            return resultBean;
        }
        //修改商品销量
        List<OrderDetail> details = new ArrayList<>();
        for(String id:ids){
            details.addAll(orderDetailService.getDetailsByOrderId(id));
            //修改用户积分
            Order order = orderService.queryById(id);
            Double d = order.getOriginalPrice()*100;
            flag = userService.updateUserIntegral(d.intValue(),order.getUserId())>0;
        }
        for(OrderDetail detail:details){
            flag = goodsService.updateGoodsSale(detail.getGoodsId(),detail.getAmount())>0;
        }
        if(!flag){
            return new ResultBean("收获失败！",false,null);
        }
        resultBean.setSuccess(orderService.changeOrderStatus(ids,"FINISH"));
        if(!resultBean.isSuccess()){
            resultBean.setMsg("收货失败！");
            return resultBean;
        }
        resultBean.setMsg("收货成功！");
        return resultBean;
    }

}